import json
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from tkinter import messagebox
from datetime import datetime
import requests
import pandas as pd

# ===========================================================================================
y_gz_time = []  # 保存某基金的所有的历史净值
y_gz = []  # 保存某基金最近更新的历史净值
y_gzf = []  # 保存某基金最近更新的历史净值的时间


def goto_email(file_path, title):
    smtp_server = "smtp.qq.com"
    smtp_port = 465
    sender_email = "929463988@qq.com"  # 替换为你的QQ邮箱
    password = r"ulbibkjhjkakbfgb"  # 替换为QQ邮箱的授权码（不是密码！）
    with open(file_path, 'r', encoding='utf-8') as file:
        file_content = file.read()
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = "929463988@qq.com"
    message['Subject'] = title
    message.attach(MIMEText(file_content, 'plain'))
    attachment = MIMEText(file_content)
    attachment.add_header('Content-Disposition', 'attachment', filename="file.txt")
    message.attach(attachment)
    try:
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(sender_email, password)
            server.send_message(message)
    except smtplib.SMTPResponseException as e:
        if e.smtp_code == -1:  # 如果是 QQ 邮箱的奇怪响应
            pass
        else:
            messagebox.showinfo('提醒', f"SMTP 错误: {e}")
    except Exception as e:
        messagebox.showinfo('提醒', f"邮件发送失败: {e}")


def y_get_gz(fund_code):
    url = f"http://fundgz.1234567.com.cn/js/{fund_code}.js?rt={int(datetime.now().timestamp())}"
    headers = {'Referer': 'http://fund.eastmoney.com/', 'User-Agent': 'Mozilla/5.0'}
    response = requests.get(url, headers=headers, timeout=20)
    data = json.loads(response.text.replace("jsonpgz(", "").replace(");", ""))
    y_gz_time.append({data['gztime']})  # 保存获取的估值时间
    y_gz.append(float(data['gsz']))  # 保存获取的估值
    y_gzf.append(data['gszzl'])


if __name__ == '__main__':
    now_time = datetime.now().strftime('%m月%d日')
    y_get_gz('023948')
    jj_y = pd.read_excel('../Fund_form_files/Y策略验证基金.xlsx')
    y_jj_jz = jj_y['买入净值'].values
    y_jj_fe = jj_y['买入份额'].values
    min_shop_dj = y_jj_jz[len(y_jj_jz) - 1]
    jl = (y_gz[0] - min_shop_dj) / min_shop_dj * 100
    print('银华品质消费股票C(023948)')
    with open(f'分析报告/{now_time}Y策略判断报告', 'w', encoding='utf-8') as f2:
        f2.write('🏆银华品质消费股票C(023948)\n')
        f2.write(f'🛒最小净值:{min_shop_dj}\n🛒当日估值:{y_gz[0]}\n')
        f2.write(f'📈策略涨幅:{jl:.2f}%\n')
        if jl >= 1:
            print(f'可卖出{y_jj_fe[len(y_jj_jz) - 1]}份基金')
            f2.write(f'🧐卖出{y_jj_fe[len(y_jj_jz) - 1]}份')
        elif jl <= -1:
            print('买100')
            f2.write(f'🧐买')
        else:
            print('今天不动')
            f2.write('🧐没有明显信号')
    goto_email(f'分析报告/{now_time}Y策略判断报告', 'Y策略今日操作')
